<?php
/**
 * 全局违规记录管理页面
 * 功能：展示和管理所有考试项目的违规记录
 * 权限：仅考试项目管理员可访问
 * 重构版本：支持全局访问，无需exam_id参数
 */

// 开启会话
session_start();

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 为navigation.php设置必需变量
$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    $_SESSION['error_message'] = "数据库连接失败：" . $e->getMessage();
    header('Location: user_home.php');
    exit();
}

// 包含统一导航栏
if (file_exists('common/navigation.php')) {
    include_once 'common/navigation.php';
}

// 权限验证 - 使用navigation.php提供的getUserRoles函数
$user_roles = getUserRoles($current_user_id);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 初始化变量
$violations = [];
$error_message = '';
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

// 获取筛选参数
$filter_severity = $_GET['severity'] ?? '';
$filter_type = $_GET['type'] ?? '';
$filter_exam = $_GET['exam'] ?? '';

// 获取全局违规记录
try {
    $where_conditions = [];
    $params = [];
    $param_types = '';

    // 构建筛选条件
    if (!empty($filter_severity)) {
        $where_conditions[] = "v.severity_level = ?";
        $params[] = $filter_severity;
        $param_types .= 's';
    }

    if (!empty($filter_type)) {
        $where_conditions[] = "v.violation_type LIKE ?";
        $params[] = "%{$filter_type}%";
        $param_types .= 's';
    }

    if (!empty($filter_exam)) {
        $where_conditions[] = "v.exam_name LIKE ?";
        $params[] = "%{$filter_exam}%";
        $param_types .= 's';
    }

    $where_clause = '';
    if (!empty($where_conditions)) {
        $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
    }

    // 修复SQL查询：移除不存在的字段 s.department 和 s.position
    $violations_sql = "SELECT v.*, s.name as staff_name
                       FROM violations v 
                       LEFT JOIN staff s ON v.invigilator_id = s.user_id 
                       {$where_clause}
                       ORDER BY v.violation_date DESC, v.created_at DESC";

    if (!empty($params)) {
        $violations_stmt = $conn->prepare($violations_sql);
        if (!$violations_stmt) {
            throw new Exception("准备查询违规记录失败: " . $conn->error);
        }

        $violations_stmt->bind_param($param_types, ...$params);
        $violations_stmt->execute();
        $violations_result = $violations_stmt->get_result();

        while ($row = $violations_result->fetch_assoc()) {
            $violations[] = $row;
        }
        $violations_stmt->close();
    } else {
        $violations_result = $conn->query($violations_sql);
        if ($violations_result) {
            while ($row = $violations_result->fetch_assoc()) {
                $violations[] = $row;
            }
        }
    }

} catch (Exception $e) {
    $error_message = "获取违规记录失败: " . $e->getMessage();
    error_log($error_message);
}

// 获取统计数据
$stats = [
    'total' => count($violations),
    'minor' => count(array_filter($violations, function($v) { return $v['severity_level'] === '轻微'; })),
    'normal' => count(array_filter($violations, function($v) { return $v['severity_level'] === '一般'; })),
    'serious' => count(array_filter($violations, function($v) { return $v['severity_level'] === '严重'; })),
    'critical' => count(array_filter($violations, function($v) { return $v['severity_level'] === '极严重'; })),
    'recent' => count(array_filter($violations, function($v) { return $v['violation_date'] >= date('Y-m-d', strtotime('-30 days')); })),
    'unique_staff' => count(array_unique(array_column($violations, 'invigilator_id'))),
    'unique_exams' => count(array_unique(array_column($violations, 'exam_id')))
];

// 严重程度颜色映射
$severity_colors = [
    '轻微' => 'success',
    '一般' => 'warning',
    '严重' => 'danger',
    '极严重' => 'dark'
];

$page_title = '违规记录管理 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        .main-content {
            margin-top: 20px;
            padding-bottom: 40px;
        }

        .page-header {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
            box-shadow: 0 8px 25px rgba(220, 53, 69, 0.3);
        }

        /* 功能增强通知 */
        .enhancement-notice {
            background: linear-gradient(135deg, #fff5f5 0%, #fed7d7 50%, #fbb6ce 100%);
            border: 1px solid #fc8181;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.1);
        }

        .enhancement-notice h6 {
            color: #c53030;
            font-weight: 700;
            margin-bottom: 12px;
            font-size: 16px;
        }

        .enhancement-notice .badge {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            margin-right: 8px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .enhancement-notice p {
            color: #742a2a;
            margin: 0;
            line-height: 1.5;
        }

        /* 统计卡片 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            border: 2px solid transparent;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #dc3545, #6f42c1);
            transform: scaleX(0);
            transition: transform 0.3s ease;
        }

        .stat-card:hover::before {
            transform: scaleX(1);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .stat-number {
            font-size: 2.2rem;
            font-weight: 800;
            margin-bottom: 8px;
            background: linear-gradient(135deg, #dc3545, #6f42c1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .stat-label {
            font-size: 14px;
            color: #495057;
            font-weight: 600;
            line-height: 1.3;
        }

        /* 筛选控制 */
        .filter-controls {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .filter-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }

        /* 违规记录卡片 */
        .violations-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
        }

        .violation-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            overflow: hidden;
            border: 1px solid #e9ecef;
        }

        .violation-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 30px rgba(0,0,0,0.15);
        }

        .card-header {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            padding: 20px;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .severity-badge {
            font-size: 12px;
            padding: 8px 16px;
            border-radius: 25px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .violation-date {
            font-size: 14px;
            color: #6c757d;
            font-weight: 600;
        }

        .card-body {
            padding: 25px;
        }

        .exam-title {
            font-size: 18px;
            font-weight: 700;
            color: #495057;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .exam-title i {
            margin-right: 10px;
            color: #dc3545;
        }

        .violation-details {
            display: grid;
            gap: 12px;
        }

        .detail-item {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #495057;
        }

        .detail-item i {
            width: 20px;
            margin-right: 10px;
            color: #6c757d;
            text-align: center;
        }

        .detail-label {
            font-weight: 600;
            margin-right: 8px;
            min-width: 80px;
        }

        .violation-description {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            border-left: 4px solid #dc3545;
        }

        .violation-description h6 {
            color: #495057;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .violation-description p {
            color: #6c757d;
            font-size: 13px;
            margin: 0;
            line-height: 1.5;
        }

        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #6c757d;
            grid-column: 1 / -1;
        }

        .empty-state i {
            font-size: 5rem;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        .btn-filter {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
            color: white;
            font-weight: 600;
        }

        .btn-filter:hover {
            background: linear-gradient(135deg, #c82333, #bd2130);
            color: white;
        }

        .btn-clear {
            background: #6c757d;
            border: none;
            color: white;
            font-weight: 600;
        }

        .btn-clear:hover {
            background: #495057;
            color: white;
        }

        @media (max-width: 768px) {
            .violations-container {
                grid-template-columns: 1fr;
            }

            .filter-row {
                grid-template-columns: 1fr;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .card-header {
                flex-direction: column;
                gap: 10px;
                text-align: center;
            }
        }
    </style>
</head>
<body>
<!-- 统一导航栏已通过navigation.php包含 -->

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="mb-2">
            <i class="fas fa-shield-alt"></i> 违规记录管理
        </h1>
        <p class="mb-0">全局违规记录管理和监考员风险评估系统</p>
    </div>

    <!-- 功能增强通知 -->
    <div class="enhancement-notice">
        <h6><i class="fas fa-shield-alt"></i> 违规管理系统</h6>
        <p>
            <span class="badge">ENHANCED</span>
            全新违规记录管理系统，支持全局违规查看、智能筛选和风险评估。
        </p>
    </div>

    <!-- 成功消息 -->
    <?php if (!empty($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 错误消息 -->
    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 统计信息 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['total']; ?></div>
            <div class="stat-label">总违规记录</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['serious'] + $stats['critical']; ?></div>
            <div class="stat-label">严重违规</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['unique_staff']; ?></div>
            <div class="stat-label">涉及监考员</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['unique_exams']; ?></div>
            <div class="stat-label">涉及考试</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['recent']; ?></div>
            <div class="stat-label">近30天违规</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['minor']; ?></div>
            <div class="stat-label">轻微违规</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['normal']; ?></div>
            <div class="stat-label">一般违规</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['critical']; ?></div>
            <div class="stat-label">极严重违规</div>
        </div>
    </div>

    <!-- 筛选控制 -->
    <div class="filter-controls">
        <h5 class="mb-3"><i class="fas fa-filter"></i> 筛选条件</h5>
        <form method="GET" class="filter-form">
            <div class="filter-row">
                <div>
                    <label class="form-label">严重程度</label>
                    <select name="severity" class="form-select">
                        <option value="">全部严重程度</option>
                        <option value="轻微" <?php echo ($filter_severity === '轻微') ? 'selected' : ''; ?>>轻微</option>
                        <option value="一般" <?php echo ($filter_severity === '一般') ? 'selected' : ''; ?>>一般</option>
                        <option value="严重" <?php echo ($filter_severity === '严重') ? 'selected' : ''; ?>>严重</option>
                        <option value="极严重" <?php echo ($filter_severity === '极严重') ? 'selected' : ''; ?>>极严重</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">违规类型</label>
                    <input type="text" name="type" class="form-control" placeholder="搜索违规类型..." value="<?php echo htmlspecialchars($filter_type); ?>">
                </div>
                <div>
                    <label class="form-label">考试项目</label>
                    <input type="text" name="exam" class="form-control" placeholder="搜索考试项目..." value="<?php echo htmlspecialchars($filter_exam); ?>">
                </div>
                <div>
                    <button type="submit" class="btn btn-filter">
                        <i class="fas fa-search"></i> 筛选
                    </button>
                    <a href="violations_display_all.php" class="btn btn-clear ms-2">
                        <i class="fas fa-times"></i> 清除
                    </a>
                </div>
            </div>
        </form>
    </div>

    <!-- 违规记录卡片 -->
    <div class="violations-container">
        <?php if (empty($violations)): ?>
            <!-- 空状态 -->
            <div class="empty-state">
                <i class="fas fa-clipboard-check"></i>
                <h4>暂无违规记录</h4>
                <p class="mb-3">系统中暂时没有符合条件的违规记录</p>
                <a href="exam_projects.php" class="btn btn-filter">
                    <i class="fas fa-plus"></i> 前往项目管理添加违规记录
                </a>
            </div>
        <?php else: ?>
            <?php foreach ($violations as $violation): ?>
                <div class="violation-card">
                    <div class="card-header">
                            <span class="severity-badge bg-<?php echo $severity_colors[$violation['severity_level']] ?? 'secondary'; ?>">
                                <?php echo htmlspecialchars($violation['severity_level']); ?>
                            </span>
                        <div class="violation-date">
                            <i class="fas fa-calendar-alt"></i>
                            <?php echo htmlspecialchars($violation['violation_date']); ?>
                        </div>
                    </div>

                    <div class="card-body">
                        <div class="exam-title">
                            <i class="fas fa-clipboard-list"></i>
                            <?php echo htmlspecialchars($violation['exam_name']); ?>
                        </div>

                        <div class="violation-details">
                            <div class="detail-item">
                                <i class="fas fa-door-open"></i>
                                <span class="detail-label">考试场次：</span>
                                <span><?php echo htmlspecialchars($violation['exam_session'] ?? '未指定'); ?></span>
                            </div>

                            <div class="detail-item">
                                <i class="fas fa-user"></i>
                                <span class="detail-label">监考员：</span>
                                <span><?php echo htmlspecialchars($violation['invigilator_name']); ?></span>
                                <small class="text-muted ms-2">(<?php echo htmlspecialchars($violation['invigilator_id']); ?>)</small>
                            </div>

                            <div class="detail-item">
                                <i class="fas fa-exclamation-circle"></i>
                                <span class="detail-label">违规类型：</span>
                                <span><?php echo htmlspecialchars($violation['violation_type']); ?></span>
                            </div>

                            <div class="detail-item">
                                <i class="fas fa-minus-circle"></i>
                                <span class="detail-label">违反纪律积分：</span>
                                <span class="badge bg-danger"><?php echo number_format($violation['disciplinary_violation_points'] ?? 0, 1); ?> 分</span>
                            </div>

                            <div class="detail-item">
                                <i class="fas fa-clock"></i>
                                <span class="detail-label">记录时间：</span>
                                <span><?php echo date('Y-m-d H:i', strtotime($violation['created_at'])); ?></span>
                            </div>
                        </div>

                        <?php if (!empty($violation['description'])): ?>
                            <div class="violation-description">
                                <h6><i class="fas fa-file-alt"></i> 详细描述</h6>
                                <p><?php echo nl2br(htmlspecialchars($violation['description'])); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('全局违规记录管理页面加载完成');

        // 添加卡片动画效果
        const cards = document.querySelectorAll('.violation-card');
        cards.forEach((card, index) => {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';

            setTimeout(() => {
                card.style.transition = 'all 0.5s ease';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, index * 100);
        });

        // 统计卡片点击效果
        const statCards = document.querySelectorAll('.stat-card');
        statCards.forEach(card => {
            card.addEventListener('click', function() {
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = '';
                }, 150);
            });
        });
    });
</script>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>